<script setup>
import { ref, onMounted, computed } from 'vue';

// 数据
const regions = ref([]);
const cities = ref([]);
const loading = ref(true);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const showAddRegionModal = ref(false);
const showEditRegionModal = ref(false);
const showAddCityModal = ref(false);
const showEditCityModal = ref(false);
const currentRegion = ref(null);
const currentCity = ref(null);
const activeTab = ref('regions'); // 'regions' or 'cities'

// 新增/编辑表单
const regionForm = ref({
  region_name: ''
});

const cityForm = ref({
  city_name: '',
  region_id: ''
});

// 过滤后的地区列表
const filteredRegions = computed(() => {
  if (!searchQuery.value) return regions.value;
  
  const query = searchQuery.value.toLowerCase();
  return regions.value.filter(region => 
    region.region_name.toLowerCase().includes(query)
  );
});

// 过滤后的城市列表
const filteredCities = computed(() => {
  let result = cities.value;
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(city => 
      city.city_name.toLowerCase().includes(query) ||
      city.region_name?.toLowerCase().includes(query)
    );
  }
  
  return result;
});

// 分页数据
const paginatedData = computed(() => {
  const data = activeTab.value === 'regions' ? filteredRegions.value : filteredCities.value;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return data.slice(start, end);
});

// 总页数
const totalPages = computed(() => {
  const data = activeTab.value === 'regions' ? filteredRegions.value : filteredCities.value;
  return Math.ceil(data.length / pageSize.value);
});

onMounted(() => {
  fetchRegionsAndCities();
});

// 模拟获取地区和城市数据
const fetchRegionsAndCities = () => {
  loading.value = true;
  
  // 模拟API调用
  setTimeout(() => {
    // 地区数据
    regions.value = [
      { id: 1, region_name: '华东地区' },
      { id: 2, region_name: '华南地区' },
      { id: 3, region_name: '华北地区' },
      { id: 4, region_name: '西南地区' },
      { id: 5, region_name: '西北地区' },
      { id: 6, region_name: '东北地区' },
      { id: 7, region_name: '华中地区' }
    ];
    
    // 城市数据
    cities.value = [
      { id: 1, city_name: '上海', region_id: 1, region_name: '华东地区' },
      { id: 2, city_name: '杭州', region_id: 1, region_name: '华东地区' },
      { id: 3, city_name: '南京', region_id: 1, region_name: '华东地区' },
      { id: 4, city_name: '广州', region_id: 2, region_name: '华南地区' },
      { id: 5, city_name: '深圳', region_id: 2, region_name: '华南地区' },
      { id: 6, city_name: '北京', region_id: 3, region_name: '华北地区' },
      { id: 7, city_name: '天津', region_id: 3, region_name: '华北地区' },
      { id: 8, city_name: '成都', region_id: 4, region_name: '西南地区' },
      { id: 9, city_name: '重庆', region_id: 4, region_name: '西南地区' },
      { id: 10, city_name: '西安', region_id: 5, region_name: '西北地区' },
      { id: 11, city_name: '兰州', region_id: 5, region_name: '西北地区' },
      { id: 12, city_name: '沈阳', region_id: 6, region_name: '东北地区' },
      { id: 13, city_name: '大连', region_id: 6, region_name: '东北地区' },
      { id: 14, city_name: '武汉', region_id: 7, region_name: '华中地区' },
      { id: 15, city_name: '长沙', region_id: 7, region_name: '华中地区' }
    ];
    
    loading.value = false;
  }, 800);
};

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab;
  currentPage.value = 1;
};

// 打开新增地区模态框
const openAddRegionModal = () => {
  regionForm.value = { region_name: '' };
  showAddRegionModal.value = true;
};

// 打开编辑地区模态框
const openEditRegionModal = (region) => {
  currentRegion.value = { ...region };
  regionForm.value = { region_name: region.region_name };
  showEditRegionModal.value = true;
};

// 打开新增城市模态框
const openAddCityModal = () => {
  cityForm.value = {
    city_name: '',
    region_id: regions.value.length > 0 ? regions.value[0].id : ''
  };
  showAddCityModal.value = true;
};

// 打开编辑城市模态框
const openEditCityModal = (city) => {
  currentCity.value = { ...city };
  cityForm.value = {
    city_name: city.city_name,
    region_id: city.region_id
  };
  showEditCityModal.value = true;
};

// 删除地区
const deleteRegion = (regionId) => {
  // 检查是否有城市关联此地区
  const hasCities = cities.value.some(city => city.region_id === regionId);
  if (hasCities) {
    alert('该地区下还有城市，无法删除');
    return;
  }
  
  if (confirm('确定要删除该地区吗？')) {
    regions.value = regions.value.filter(region => region.id !== regionId);
  }
};

// 删除城市
const deleteCity = (cityId) => {
  if (confirm('确定要删除该城市吗？')) {
    cities.value = cities.value.filter(city => city.id !== cityId);
  }
};

// 提交新增地区
const submitAddRegion = () => {
  if (!regionForm.value.region_name.trim()) {
    alert('请输入地区名称');
    return;
  }
  
  const newRegion = {
    id: Date.now(),
    region_name: regionForm.value.region_name.trim()
  };
  
  regions.value.push(newRegion);
  showAddRegionModal.value = false;
};

// 提交编辑地区
const submitEditRegion = () => {
  if (!regionForm.value.region_name.trim()) {
    alert('请输入地区名称');
    return;
  }
  
  const index = regions.value.findIndex(region => region.id === currentRegion.value.id);
  if (index !== -1) {
    const oldName = regions.value[index].region_name;
    regions.value[index].region_name = regionForm.value.region_name.trim();
    
    // 更新关联城市的地区名称
    cities.value.forEach(city => {
      if (city.region_id === currentRegion.value.id) {
        city.region_name = regionForm.value.region_name.trim();
      }
    });
  }
  
  showEditRegionModal.value = false;
};

// 提交新增城市
const submitAddCity = () => {
  if (!cityForm.value.city_name.trim()) {
    alert('请输入城市名称');
    return;
  }
  
  if (!cityForm.value.region_id) {
    alert('请选择所属地区');
    return;
  }
  
  const region = regions.value.find(r => r.id === parseInt(cityForm.value.region_id));
  
  const newCity = {
    id: Date.now(),
    city_name: cityForm.value.city_name.trim(),
    region_id: parseInt(cityForm.value.region_id),
    region_name: region ? region.region_name : ''
  };
  
  cities.value.push(newCity);
  showAddCityModal.value = false;
};

// 提交编辑城市
const submitEditCity = () => {
  if (!cityForm.value.city_name.trim()) {
    alert('请输入城市名称');
    return;
  }
  
  if (!cityForm.value.region_id) {
    alert('请选择所属地区');
    return;
  }
  
  const index = cities.value.findIndex(city => city.id === currentCity.value.id);
  if (index !== -1) {
    const region = regions.value.find(r => r.id === parseInt(cityForm.value.region_id));
    
    cities.value[index] = {
      ...cities.value[index],
      city_name: cityForm.value.city_name.trim(),
      region_id: parseInt(cityForm.value.region_id),
      region_name: region ? region.region_name : ''
    };
  }
  
  showEditCityModal.value = false;
};

// 分页控制
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
  }
};
</script>

<template>
  <div>
    <div class="mb-6">
      <h2 class="text-2xl font-bold text-gray-900">地区管理</h2>
      <p class="text-gray-600">管理平台的地区和城市数据</p>
    </div>

    <!-- 标签页切换 -->
    <div class="border-b border-gray-200 mb-4">
      <nav class="-mb-px flex space-x-8">
        <button
          @click="switchTab('regions')"
          class="border-b-2 px-1 pt-1 text-sm font-medium"
          :class="activeTab === 'regions' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
        >
          地区管理
        </button>
        <button
          @click="switchTab('cities')"
          class="border-b-2 px-1 pt-1 text-sm font-medium"
          :class="activeTab === 'cities' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
        >
          城市管理
        </button>
      </nav>
    </div>

    <!-- 搜索和添加按钮 -->
    <div class="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between">
      <div class="relative rounded-md shadow-sm w-full sm:w-auto mb-3 sm:mb-0">
        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
          <i class="fa fa-search text-gray-400"></i>
        </div>
        <input 
          type="text" 
          v-model="searchQuery"
          class="block w-full rounded-md border-gray-300 pl-10 pr-3 py-2 text-sm placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary"
          :placeholder="activeTab === 'regions' ? '搜索地区名称' : '搜索城市名称或地区名称'"
        >
      </div>
      <button 
        @click="activeTab === 'regions' ? openAddRegionModal() : openAddCityModal()"
        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
      >
        <i class="fa fa-plus mr-2"></i> 
        {{ activeTab === 'regions' ? '添加地区' : '添加城市' }}
      </button>
    </div>

    <!-- 列表 -->
    <div class="bg-white shadow overflow-hidden rounded-lg">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th v-if="activeTab === 'regions'" scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                地区名称
              </th>
              <template v-else>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  城市名称
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  所属地区
                </th>
              </template>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <template v-if="loading">
              <tr v-for="i in 5" :key="i">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-5 bg-gray-200 rounded animate-pulse"></div>
                </td>
                <td v-if="activeTab === 'cities'" class="px-6 py-4 whitespace-nowrap">
                  <div class="h-5 bg-gray-200 rounded animate-pulse"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <div class="flex justify-end space-x-2">
                    <div class="h-8 w-8 bg-gray-200 rounded animate-pulse"></div>
                    <div class="h-8 w-8 bg-gray-200 rounded animate-pulse"></div>
                  </div>
                </td>
              </tr>
            </template>
            <template v-else>
              <tr v-for="item in paginatedData" :key="item.id" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900">{{ activeTab === 'regions' ? item.region_name : item.city_name }}</div>
                </td>
                <td v-if="activeTab === 'cities'" class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-500">{{ item.region_name }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button 
                    @click="activeTab === 'regions' ? openEditRegionModal(item) : openEditCityModal(item)"
                    class="text-primary hover:text-primary/80 mr-3"
                  >
                    编辑
                  </button>
                  <button 
                    @click="activeTab === 'regions' ? deleteRegion(item.id) : deleteCity(item.id)"
                    class="text-red-600 hover:text-red-800"
                  >
                    删除
                  </button>
                </td>
              </tr>
              <tr v-if="paginatedData.length === 0">
                <td :colspan="activeTab === 'regions' ? 2 : 3" class="px-6 py-10 text-center text-gray-500">
                  没有找到匹配的{{ activeTab === 'regions' ? '地区' : '城市' }}
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="!loading && totalPages > 1" class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
        <div class="flex-1 flex justify-between sm:hidden">
          <button 
            @click="changePage(currentPage - 1)"
            :disabled="currentPage === 1"
            class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
          >
            上一页
          </button>
          <button 
            @click="changePage(currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
          >
            下一页
          </button>
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700">
              显示 <span class="font-medium">{{ Math.max(1, (currentPage - 1) * pageSize + 1) }}</span> 到 <span class="font-medium">{{ Math.min(currentPage * pageSize, activeTab === 'regions' ? filteredRegions.length : filteredCities.length) }}</span> 条，共 <span class="font-medium">{{ activeTab === 'regions' ? filteredRegions.length : filteredCities.length }}</span> 条结果
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
              <button 
                @click="changePage(currentPage - 1)"
                :disabled="currentPage === 1"
                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
              >
                <i class="fa fa-chevron-left"></i>
              </button>
              <button 
                v-for="page in Math.min(5, totalPages)"
                :key="page"
                @click="changePage(page)"
                class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50"
                :class="{ 'bg-primary text-white': currentPage === page }"
              >
                {{ page }}
              </button>
              <button 
                @click="changePage(currentPage + 1)"
                :disabled="currentPage === totalPages"
                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
              >
                <i class="fa fa-chevron-right"></i>
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加地区模态框 -->
    <div v-if="showAddRegionModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">添加新地区</h3>
        </div>
        <div class="px-6 py-4">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">地区名称</label>
              <input 
                type="text" 
                v-model="regionForm.region_name"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
          </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
          <button 
            @click="showAddRegionModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="submitAddRegion"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90"
          >
            添加
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑地区模态框 -->
    <div v-if="showEditRegionModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">编辑地区</h3>
        </div>
        <div class="px-6 py-4">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">地区名称</label>
              <input 
                type="text" 
                v-model="regionForm.region_name"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
          </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
          <button 
            @click="showEditRegionModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="submitEditRegion"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90"
          >
            保存
          </button>
        </div>
      </div>
    </div>

    <!-- 添加城市模态框 -->
    <div v-if="showAddCityModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">添加新城市</h3>
        </div>
        <div class="px-6 py-4">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">城市名称</label>
              <input 
                type="text" 
                v-model="cityForm.city_name"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所属地区</label>
              <select 
                v-model="cityForm.region_id"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
                <option v-for="region in regions" :key="region.id" :value="region.id">
                  {{ region.region_name }}
                </option>
              </select>
            </div>
          </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
          <button 
            @click="showAddCityModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="submitAddCity"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90"
          >
            添加
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑城市模态框 -->
    <div v-if="showEditCityModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">编辑城市</h3>
        </div>
        <div class="px-6 py-4">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">城市名称</label>
              <input 
                type="text" 
                v-model="cityForm.city_name"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所属地区</label>
              <select 
                v-model="cityForm.region_id"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
                <option v-for="region in regions" :key="region.id" :value="region.id">
                  {{ region.region_name }}
                </option>
              </select>
            </div>
          </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
          <button 
            @click="showEditCityModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="submitEditCity"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:root {
  --primary-color: #4f46e5;
}

.bg-primary {
  background-color: var(--primary-color);
}

.text-primary {
  color: var(--primary-color);
}

.border-primary {
  border-color: var(--primary-color);
}

.hover\:text-primary\/80:hover {
  color: rgba(79, 70, 229, 0.8);
}

.hover\:bg-primary\/90:hover {
  background-color: rgba(79, 70, 229, 0.9);
}

.focus\:ring-primary:focus {
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.5);
}

.focus\:border-primary:focus {
  border-color: var(--primary-color);
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}
</style>